import {
    Table, Space, Card, Form, Button, Checkbox, Input, Select,
    // InputNumber
} from 'antd'
import { useStore } from '@/store'
import React, { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import {
    http
    // , NumberInputChange 
} from '@/utils'
import { DebounceSelect } from '@/components/DebounceSelect'
import { NumericInput } from '@/components/NumericInput'
import Tmptransfer from './components/Tmptransfer'
import { useNavigate } from 'react-router-dom'
import './index.scss'
// Usage of DebounceSelect

const Variety = () => {
    const [form] = Form.useForm()
    const [varietyData, setVarietyData] = useState({
        list: [],
        count: 0
    })
    const [defaultopt, setDefaultopt] = useState([])
    const [dict_data, setDict_data] = useState([])
    // const [endScore, setEndScore] = useState(null)
    // const [startScore, setStartScore] = useState(null)

    const { loginStore } = useStore()
    const [paramsUrl] = useSearchParams()
    const [factorListOpt, setFactorList] = useState([])
    const groupRow = {
        key: paramsUrl.get('groupId'),
        label: paramsUrl.get('groupName'),
        value: paramsUrl.get('groupId')
    }
    const [params, setParams] = useState({
        groupId: groupRow.value || '',
        scoreInfo: {
            freqName: "",
            startScore: 0,
            endScore: 0
        },
        pageNum: 1,
        pageSize: 20
    })
    // 配置品种预警组
    const [tmpOpenModal, setTmpOpenModal] = useState(false)
    const [configRow, setConfigRow] = useState({})


    const showModalOpen = (data) => {
        setTmpOpenModal(true)
        setConfigRow(data)
    }
    const changeConfigModal = (res) => {
        setTmpOpenModal(res)
        setParams({ ...params })
    }

    const fetchUserList = async (val) => {
        return http.post('/alarm/deliversign/findAlarmGroupInfoByPage', {
            userId: loginStore.userId,
            groupAlarmName: val,
            pageNum: 1,
            pageSize: 20
        }).then(res => {
            return res.body.list.map(item => ({
                label: item.groupAlarmName,
                value: item.id,
            }))
        })
    }
    // const pageChange = (page, pageSize) => {
    //     setVarietyData({ list: [], count: 0 })
    //     setParams({
    //         ...params,
    //         pageSize: pageSize,
    //         pageNum: page
    //     })
    // }
    const onSortChange = (pagination, filters, sorter) => {
        const orderByInfo = {}
        if (sorter.column) {
            orderByInfo[sorter.column.freqKey] = sorter.order ? sorter.order.replace('end', '') : ''
        }
        setParams({
            ...params,
            orderByInfo,
            pageSize: pagination.pageSize,
            pageNum: pagination.current
        })
    }
    // const startScoreOnChange = (e) => {
    //     const val = NumberInputChange(e.target.value)
    //     setStartScore(val)
    //     // console.log(val, endScore)
    //     if (endScore && +val > +endScore) {
    //         return endScore
    //     }
    //     return val
    // }
    // const endScoreOnChange = (e) => {
    //     const val = NumberInputChange(e.target.value)
    //     setEndScore(val)
    //     // console.log(startScore, val)
    //     if (startScore && +val < +startScore) {
    //         return startScore
    //     }
    //     return val
    // }
    const onSeach = (values) => {
        const endScore = values.endScore === "0" ? 0 : +values.endScore || null
        const startScore = values.startScore === "0" ? 0 : +values.startScore || null
        const _params = {
            ...values,
            groupId: values.groupList ? values.groupList.value : '',
            exchangeId: values.exchangeId.join(','),
            optionId: values.optionId.join(','),
            scoreInfo: {
                freqName: values.freqKey,
                startScore: startScore,
                endScore: endScore
            }
        }
        // {
        //     startScore: values.startScore,
        //     endScore: values.endScore
        // }
        setParams({
            ...params,
            groupId: '',
            ..._params,
            pageNum: 1,
        })
    }
    const clearExchangeId = () => {
        form.setFieldsValue({ exchangeId: [] })
    }
    const clearOptionId = () => {
        form.setFieldsValue({ optionId: [] })
    }
    const [columns, setColumns] = useState([
        { title: '编号', dataIndex: 'id', width: 60, },
        { title: '品种代码', dataIndex: 'scode', width: 100 },
        {
            title: '品种名称', dataIndex: '', render: (data) => {
                return (<Space style={{ minWidth: 160 }}>
                    <div>{data.displayName}</div>
                    {data.soption === 2 ? <div className='trading'>主</div> : ''}
                    {/* <div>{data.alias}</div> */}
                </Space>)
            }
        },

        { title: '品种市场', dataIndex: 'sgroupName', width: 100, },
        { title: '所属预警组', dataIndex: 'alarmGroupListText', width: 400 },
        // { title: '总分', dataIndex: 'totalScore', width: 75, freqKey: 'totalScore', sorter: true },
    ])
    const navigate = useNavigate()
    const [firstLoad, setFirstLoad] = useState(false)
    useEffect(() => {
        const getList = async () => {
            const res = await http.post('/alarm/deliversign/findFeatureInfoByPage', { userId: loginStore.userId, ...params })
            console.log('品种池列表-', res.body)
            const { list, total } = res.body
            setVarietyData({
                list: list,
                count: total
            })
        }
        const getDicfig = async () => {
            const res = await http.post('/alarm/deliversign/getDicConfig', {
                userId: loginStore.userId,
                dictIds: [1000, 1001, 1002, 1003, 1004]
            })
            setDict_data(res.body)
            console.log('字典-', res.body)
            getFreq()
        }
        const goScoreLine = (data) => {
            let code = ''
            if (data.sgroupName === '外盘') {
                code = data.scode
            } else {
                code = data.scode.split('.')[0]
            }
            window.open(`./#/scoreLine?featureId=${data.id}&featureName=${data.displayName}&code=${code}`)
        }
        const goSignal = (data) => {
            // navigate(`/signal?featureId=${data.id}&featureName=${data.displayName}`)
            window.open(`./#/signal?featureId=${data.id}&featureName=${data.displayName}`)
        }
        const getFreq = async () => {
            const res = await http.post('/alarm/deliversign/getAllFreq')
            const list = res.body ? res.body.map(item => ({
                dataIndex: item.freqKey,
                value: item.freqName,
                label: item.freqName,
                freqKey: item.freqKey,
                title: item.freqName,
                sorter: true
            })) : [{ label: '暂无', value: '' }]
            console.log('周期列表-', list)
            list.unshift({
                dataIndex: 'totalScore',
                value: 'total_score',
                label: '总分',
                freqKey: 'totalScore',
                title: '总分',
                width: 70,
                sorter: true
            })
            setFactorList(list)
            setColumns([
                ...columns,
                ...list,
                {
                    width: 200,
                    title: '操作',
                    render: data => {
                        return (
                            <Space size="middle">
                                <Button size="small" onClick={() => showModalOpen(data)}>配置预警组</Button> |
                                <Button size="small" onClick={() => goScoreLine(data)}>分值趋势</Button> |
                                <Button size="small" onClick={() => goSignal(data)}>预警信号</Button>
                            </Space>
                        )
                    },
                    fixed: 'right'
                }
            ])
        }
        const fetchUserList = async (val) => {
            return http.post('/alarm/deliversign/findAlarmGroupInfoByPage', {
                userId: loginStore.userId,
                groupAlarmName: val,
                pageNum: 1,
                pageSize: 20
            }).then(res => {
                return res.body.list.map(item => ({
                    label: item.groupAlarmName,
                    value: item.id,
                }))
            })
        }
        const getfeatchList = async () => {
            const res = await fetchUserList()
            const list = res.length ? res : [{ label: '--请选择--', value: '' }]
            setFirstLoad(true)
            setDefaultopt(list)
        }
        if (!firstLoad) {
            getfeatchList()
        }
        if (firstLoad && !dict_data[1000]) {
            getDicfig()
        }
        if (firstLoad && dict_data[1000]) {
            getList()
        }
    }, [params, columns, loginStore, defaultopt, dict_data, navigate, firstLoad])

    return (
        <>
            <Card title="品种池列表">
                <Form
                    form={form}
                    onFinish={onSeach}
                    initialValues={{
                        groupList: groupRow,
                        exchangeId: [],
                        optionId: []
                    }}
                >
                    <Form.Item style={{ margin: 0 }}>
                        <Form.Item label="品种" name="keyWord" style={{ display: 'inline-block', width: 300, marginBottom: 10 }}>
                            <Input
                                allowClear
                                placeholder='请输入品种名称/代码/简称'
                                style={{ width: 240 }}
                                onChange={form.submit}
                            />
                        </Form.Item>
                        <Form.Item label="预警组名称" name="groupList" style={{ display: 'inline-block', width: 300, marginBottom: 10 }}>
                            {defaultopt.length ? <DebounceSelect
                                showSearch
                                placeholder="请选择预警组名称"
                                fetchOptions={fetchUserList}
                                allowClear
                                defaultopt={defaultopt}
                                style={{ width: 200 }}
                            /> : <Input
                                allowClear
                                placeholder='请输入预警组名称'
                                style={{ width: 200 }}
                            />}
                        </Form.Item>
                        <div className='site-input-group-wrapper'>
                            <Input.Group compact >
                                <Form.Item name="freqKey" label="周期类型" style={{ marginBottom: 10 }}>
                                    <Select
                                        allowClear
                                        placeholder='请选择周期类型'
                                        style={{ width: 150 }}
                                        options={factorListOpt}
                                        onChange={form.submit}
                                    >
                                    </Select>
                                </Form.Item>
                                <Form.Item name="startScore" style={{ marginBottom: 10 }}>
                                    <NumericInput
                                        style={{ width: 80, textAlign: 'center' }}
                                        placeholder="最小分数"
                                    />
                                </Form.Item>
                                <Form.Item name="" style={{ marginBottom: 10 }}>
                                    <Input
                                        className="site-input-split"
                                        style={{
                                            width: 30,
                                            borderLeft: 0,
                                            borderRight: 0,
                                            pointerEvents: 'none',
                                        }}
                                        placeholder="~"
                                        disabled
                                    />
                                </Form.Item>
                                <Form.Item name="endScore" style={{ marginBottom: 10 }}>
                                    <NumericInput
                                        className="site-input-right"
                                        style={{ width: 80, textAlign: 'center' }}
                                        placeholder="最大分数"
                                    />
                                </Form.Item>
                            </Input.Group>
                        </div>
                        <Form.Item style={{ display: 'inline-block', width: 100, marginBottom: 10 }}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Form.Item>

                    <Form.Item label="品种市场" style={{ margin: 0 }}>
                        <Button type="link" onClick={clearExchangeId}>不限</Button>
                        <Form.Item name="exchangeId" style={{ display: 'inline-block', margin: 0 }}>
                            <Checkbox.Group
                                options={
                                    dict_data['1000'] ? dict_data['1000'].map(item => { return { value: item.dictCode, label: item.dictName } }) : []
                                }
                                onChange={form.submit}
                            />
                        </Form.Item>
                    </Form.Item>
                    <Form.Item label="常用选项" style={{ margin: 0 }}>
                        <Button type="link" onClick={clearOptionId}>不限</Button>
                        <Form.Item name="optionId" style={{ display: 'inline-block', margin: 0 }}>
                            <Checkbox.Group
                                options={
                                    dict_data['1003'] ? dict_data['1003'].map(item => { return { value: item.dictCode, label: item.dictName } }) : []
                                }
                                onChange={form.submit}
                            />
                        </Form.Item>
                    </Form.Item>
                </Form>
                <Table
                    style={{ marginTop: 20 }}
                    rowKey="id"
                    size='middle'
                    columns={columns}
                    dataSource={varietyData.list}
                    onChange={onSortChange}
                    pagination={
                        {
                            size: 'default',
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSize: params.pageSize,
                            total: varietyData.count,
                            current: params.pageNum,
                            showTotal: (total, range) => `共 ${total} 条`,
                        }
                    }
                    bordered
                />
            </Card >
            <Tmptransfer configRow={configRow} tmpOpenModal={tmpOpenModal} changeConfigModal={changeConfigModal} />
        </>
    )
}

export default Variety